package com.zy.ems.common.util;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 常用获取客户端信息的工具
 * 
 */
public final class NetworkUtil {
    /**
     * Logger for this class
     */
    private final static Logger logger = LoggerFactory
            .getLogger(NetworkUtil.class);

    /**
     * 获取当前请求对象。
     * 
     * @return
     */
    public static HttpServletRequest getCurrenRequest() {
        return ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前请求主机IP地址，如果通过代理进来，则透过防火墙获取真实IP地址。
     * 
     * @return
     */
    public static String getCurRequestIpAddress() {
        return getIpAddress(getCurrenRequest());
    }

    /**
     * 获取请求主机IP地址，如果通过代理进来，则透过防火墙获取真实IP地址。
     * 
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        logger.debug("getIpAddress(HttpServletRequest): ");
        logger.debug("X-Forwarded-For - String ip=" + ip);
        if (StringUtils.isNotBlank(ip) && ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    return strIp;
                }
            }
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            logger.debug("Proxy-Client-IP - String ip=" + ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            logger.debug("WL-Proxy-Client-IP - String ip=" + ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            logger.debug("HTTP_CLIENT_IP - String ip=" + ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            logger.debug("HTTP_X_FORWARDED_FOR - String ip=" + ip);
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            logger.debug("getRemoteAddr - String ip=" + ip);
        }
        return ip;
    }
}
